<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="请购单号" prop="nos">
            <el-input v-model="form.nos" placeholder="保存后自动生成" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="form.customerName" placeholder="请选择客户名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="请购人" prop="userId">
            <el-select v-model="form.userId" placeholder="请选择请购人" filterable @change="selectUser" clearable>
              <el-option v-for="dict in dict.type.sys_user" ref="myselectUser"
                         :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务类型" prop="ywType">
            <el-select v-model="form.ywType" placeholder="请选择业务类型" clearable>
              <el-option v-for="dict in dict.type.yewu_type"
                         :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择采购类型" clearable>
              <el-option v-for="dict in dict.type.caigou_type"
                         :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="请购日期" prop="ddDate">
            <el-date-picker clearable
                            v-model="form.ddDate"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择请购日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="需求日期" prop="subDate">
            <el-date-picker clearable
                            v-model="form.subDate"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择需求日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请选择备注"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="dataList" ref="dragTable" row-key="id">
      <el-table-column type="index" label="序号"></el-table-column>

      <el-table-column prop="goodsBrand" label="物料选择" width="380">
        <template slot-scope="scope">
          <el-autocomplete style="width: 350px;"
                           ref="autocomplete"
                           v-model="scope.row.goodsBrand"
                           :fetch-suggestions="querySearch"
                           @keyup.enter.native="handleGoodsEnter(scope.row, scope.$index)"
                           placeholder="请输入内容"
          >
            <template #default="{ item, index }">
              <div @click="handleGoodsClick(item, scope.$index)">
                {{ item.value }}
              </div>
            </template>
          </el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column label="产品编码" align="center" prop="goodsCode"/>
      <el-table-column align="center" label="产品名称" prop="goodsName"/>
      <el-table-column align="center" label="产品型号" prop="goodModel"/>
      <el-table-column align="center" label="产品单位" prop="unit"/>
      <el-table-column label="请购数量" width="160" prop="pleaseBuyApplyCount">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.pleaseBuyApplyCount" size="mini"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="210">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remark"/>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-popconfirm :title="`确认删除 `+scope.row.goodsName+` 数据项？`"
                         @confirm="handleDelete(scope.row,scope.$index)"
                         style="margin-left: 10px;">
            <el-button icon="el-icon-delete" size="mini" slot="reference" type="text">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-col :span="24" style="text-align: center;padding-top: 20px;">
        <el-button style="width: 100%;" icon="el-icon-plus" plain type="primary" @click="addRow">添加行</el-button>
      </el-col>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitScalado" v-if="">提交请购</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

  </el-dialog>
</template>

<script>
import {addAction, deleteAction, getAction, getById, isEmpty, updateAction} from '@/api/manage'

export default {
  name: "AddqinggouIronFormList",
  dicts: ['goods_customer', 'goods_type', 'yewu_type', 'caigou_type', 'sys_user'],
  components: {
  },
  data() {
    return {
      proId: '',
      ironRecordId: '',
      // 遮罩层
      title: "铁件请购",
      loading: false,
      open: false,
      // 选中数组
      ids: [],
      proStatus: "",
      saleType: "2",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息管理表格数据
      columns: [],
      baseInfoOptions: [],
      deptOptions: [],
      userInfoOptions: [],
      form: {
        nos: null,
        code: null,
        mainId: null,
        deptName: null,
        userName: this.$store.getters.nickName,
        userId: this.$store.getters.userId,
        customerId: null,
        customerName: null,
        ywType: null,
        type: '7',
        ddDate: null,
        subDate: null,
        remark: null,
      },
      rules: {
        customerName: [
          {required: true, message: "客户名称不能为空", trigger: "blur"},
        ],
        userId: [
          {required: true, message: "请购人不能为空", trigger: "blur"},
        ],
      },
      // 查询参数
      queryParams: {
        mainId: null,
        pageSizeZero: true,
      },
      dataList: [],
      url: {
        remove: '/goodsSaledo/goodsSaledo/',
        submitIron: '/goodsSaledo/goodsSaledo/insertBatchIron',
        updateIron: '/goodsSaledo/goodsSaledo/updateIron',
        listDo: '/goodsSaledo/goodsSaledo/list',
        userInfoList: '/system/user/list',
      },
      tableMaxHeight: window.innerHeight - 900,
      goodsList: [],
      goodsQueryParams: {
        name: null,
        queryLabel: null,
        pageNum: 1,
        pageSize: 20,
      },
    };
  },
  created() {
  },
  mounted() {
  },
  beforeDestroy() {
  },
  methods: {
    getUser() {
      let params = {
        pageNum: 1,
        pageSize: 1000,
      };
      getAction(this.url.userInfoList, params).then(response => {
        this.userInfoOptions = response.rows;
      });
    },
    selectUser(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectUser;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.userName = arr[i].label;
          }
        }
      })
    },

    getList() {
      this.loading = true;
      getAction(this.url.listDo, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.loading = false;
      });
    },

    handleAdd() {
      this.open = true;
      this.loading = false;
      this.reset();
      this.form.source = "2";
      this.dataList = [];
      for (let i = 0; i < 10; i++) {
        this.dataList.push({
          goodsType: '0',//产品类别
          goodsId: '',//产品编号
          goodsCode: '',//产品编号
          goodsName: '',//名称
          goodModel: '',
        })
      }
    },

    handleUpdate(row) {
      this.open = true;
      this.queryParams.mainId = row.id;
      this.form = row;
      this.getList();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        nos: null,
        code: null,
        mainId: null,
        deptId: null,
        deptName: null,
        userName: this.$store.getters.nickName,
        userId: this.$store.getters.userId,
        customerId: null,
        customerName: null,
        ywType: "1",
        type: "7",
        ddDate: new Date(),
        subDate: null,
        remark: null,
      };
      this.resetForm("form");
    },
    refreshPageData() {
      let that = this;
      let param = {
        id: that.proId
      }
    },

    handleDelete(row, index) {
      const ids = row.id || this.ids;
      if (isEmpty(ids)) {
        this.$nextTick(() => {
          this.dataList.splice(index, 1)
        })
      } else {
        deleteAction(this.url.remove, ids).then(response => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.resetForm("queryForm"); // 清空搜索条件

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    submitScalado() {
      let that = this;
      // dataList 中 goodsId 是空的 去除
      // that.dataList = that.dataList.filter(item => !isEmpty(item.goodsId));
      // 先判断提交的数据是否符合要求 dataList 中 goodsId不能全为空
      let flag = false;
      for (let i = 0; i < that.dataList.length; i++) {
        if (!isEmpty(that.dataList[i].goodsId)) {
          flag = true;
          break;
        }
      }
      if (!flag) {
        that.$modal.msgError("请选择产品后提交！");
        return;
      }
      for (let i = 0; i < that.dataList.length; i++) {
        if (!isEmpty(that.dataList[i].goodsId) && (isEmpty(that.dataList[i].pleaseBuyApplyCount) || that.dataList[i].pleaseBuyApplyCount === 0)) {
          that.$modal.msgError("产品：" + that.dataList[i].goodsName + ",请购数量不能为空或0！");
          return;
        }
      }

      that.$refs["form"].validate(valid => {
        if (valid) {
          that.form.goodsSaledoList = that.dataList;
          if (that.form.id != null) {
            updateAction(that.url.updateIron, that.form).then(response => {
              that.$modal.msgSuccess("修改成功");
              that.open = false;
              that.$emit('ok');
            });
          } else {
            addAction(this.url.submitIron, that.form).then(response => {
              that.$emit('ok');
              that.$modal.msgSuccess("提交请购成功!");
              that.open = false;
              that.handleQuery();
            }).catch(() => {
            });
          }
        }
      });
    },

    querySearch(queryLabel, cb) {
      let that = this;
      that.goodsQueryParams.queryLabel = queryLabel;
      getAction('/goodsOrderIn/goodsOrderIn/list', that.goodsQueryParams).then(response => {
        that.goodsList = response.rows;
        for (let i = 0; i < this.goodsList.length; i++) {
          that.goodsList[i].value = that.goodsList[i].name + '-' + that.goodsList[i].model + '-' + that.goodsList[i].code;
        }
        const goodsList = that.goodsList;
        const results = queryLabel
          ? goodsList.filter(that.createFilter(queryLabel))
          : goodsList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().includes(queryString.toLowerCase())
        );
      };
    },
    //点击按钮添加空行
    addRow() {
      this.$nextTick(() => {
        this.dataList.push({
          goodsType: '0',//产品类型
          code: '',//产品编号
          goodsName: '',//名称
          goodModel: '',
        })
      })
    },

    handleGoodsEnter(row, index) {
      const matchedItem = this.goodsList.find(
        item => item.name + '-' + item.model + '-' + item.code === row.goodsBrand
      )

      if (matchedItem) {
        this.$nextTick(() => {
          let newItem = {
            goodsId: matchedItem.id,
            goodsCode: matchedItem.code, //产品编号
            goodsName: matchedItem.name, //名称
            goodModel: matchedItem.model,//型号
            unit: matchedItem.unit, // 单位
            goodsBrand: matchedItem.name + '-' + matchedItem.model + '-' + matchedItem.code, // 品牌
            goodsType: '0', // 类别
          }
          this.$set(this.dataList, index, newItem)
        })
      } else {
        console.log('输入值:', this.inputValue)
        // 处理没有匹配项的情况
      }

    },

    handleGoodsClick(item, index) {
      this.$nextTick(() => {
        let newItem = {
          goodsId: item.id,
          goodsCode: item.code, //产品编号
          goodsName: item.name, //名称
          goodModel: item.model,//型号
          unit: item.unit, // 单位
          goodsBrand: item.brand, // 品牌
          goodsType: '0', // 类别
        }
        this.$set(this.dataList, index, newItem)
      })
    },


  }
};
</script>
